/***********************************************************************
    filename:   Dater.cpp
    created:    25/3/2012
    author:     4Ys
*************************************************************************/
#include "Dater.h"
#include "CEGUI.h"
#include "CEGuiBaseApplication.h"
#include "DaterMainIconWindow.h"
#include "DaterEventEditWindow.h"
#include "DaterLoginWindow.h"
#include "DaterRegisterWindow.h"
#include "DaterBaseWindowManager.h"
#include "DaterMainCalendarDayWindow.h"
#include "DaterMainCalendarMonthWindow.h"
#include "DaterMainCalendarManagerWindow.h"
#include "DaterMainGroupManagerWindow.h"
#include "4YsXMLParserEvent.h"
#include "DaterFrameWindowEffect.h"
#include "AnimationSakura.h"
#include "AnimationWindowTrans.h"
#include "DaterSystem.h"

#include "DaterCommon.h"

//----------------------------------------------------------------------------//
bool DaterApp::initialiseSample()
{
    using namespace CEGUI;

	new BaseWindowManager();

	//initialise the effect
	//RenderEffectManager::getSingleton().addEffect<DaterFrameWindowEffect>("WobblyWindow");

	/*WindowFactoryManager::getSingleton().addFalagardWindowMapping(
        "WindowsLook/DaterFrameWindow",    // type to create
        "CEGUI/FrameWindow",                // 'base' widget type
        "WindowsLook/FrameWindow",          // WidgetLook to use.
        "Falagard/FrameWindow",             // WindowRenderer to use.
        "WobblyWindow");                    // effect to use.
	*/

	// load windows look
    SchemeManager::getSingleton().create("WindowsLook.scheme");
	SchemeManager::getSingleton().create("OgreTray.scheme");
	//SchemeManager::getSingleton().create("SleekSpace.scheme");

    // load font and setup default if not loaded via scheme
    //FontManager::getSingleton().create("DejaVuSans-10.font");
	//FontManager::getSingleton().create("Chinese.font");
	FontManager::getSingleton().create("Chinese-12.font");
	//chn_font.setProperty ("PointSize", PropertyHelper::intToString(20));
	
    // set up defaults
    //System::getSingleton().setDefaultMouseCursor("SleekSpace", "MouseArrow");
	System::getSingleton().setDefaultMouseCursor("WindowsLook", "MouseArrow");
    System::getSingleton().setDefaultFont("Chinese-12");

    // load the drive icons imageset
	ImagesetManager::getSingleton().create("4YsIcon.imageset");
	ImagesetManager::getSingleton().create("Sakura.imageset");
	//ImagesetManager::getSingleton().create("HeadPhoto.imageset");

	AnimationManager::getSingleton().loadAnimationsFromXML("AnimationTrans.xml");
	AnimationManager::getSingleton().loadAnimationsFromXML("Sakura.xml");

	// load an image to use as a background
    ImagesetManager::getSingleton().createFromImageFile("BackgroundImage", "sakura1.jpg");

	// here we will use a StaticImage as the root, then we can use it to place a background image
	Window* background = WindowManager::getSingleton().createWindow("WindowsLook/StaticImage", "Background");
	// set position and size
    background->setPosition(UVector2(cegui_reldim(0), cegui_reldim( 0)));
    background->setSize(UVector2(cegui_reldim(1), cegui_reldim( 1)));
    // disable frame and standard background
    background->setProperty("FrameEnabled", "false");
    background->setProperty("BackgroundEnabled", "false");
    // set the background image
    background->setProperty("Image", "set:BackgroundImage image:full_image");
    // install this as the root GUI sheet
    System::getSingleton().setGUISheet(background);

	Window* scaleGroup[20];
	Window* imageGroup[20];
	std::string str[20] = {"1","2","3","4","5","6","7","8","9","10","111","211","311","411","511","611","711","811","911","1110"};
	std::string str2[20] = {"11","22","33","44","55","66","77","88","99","010","11111","2112","3131","4114","5115","616","7171","8181","991","01110"};
	for(int i = 0; i < 20; i++){
		scaleGroup[i] = WindowManager::getSingleton().createWindow("WindowsLook/Static",str[i]);
		scaleGroup[i] ->setXPosition(CEGUI::UDim(0,random(0,600)));
		scaleGroup[i] ->setYPosition(CEGUI::UDim(0,150));
		scaleGroup[i] ->setWidth(CEGUI::UDim(0,200+50*random(0,1)));
		scaleGroup[i] ->setHeight(CEGUI::UDim(0,600));
		scaleGroup[i] ->setProperty(("FrameEnabled"), ("false"));
		scaleGroup[i] ->setProperty(("BackgroundEnabled"), ("false"));
		scaleGroup[i] ->setMousePassThroughEnabled(true);
		//scaleGroup[i] ->setAlwaysOnTop(true);
		imageGroup[i] = WindowManager::getSingleton().createWindow("WindowsLook/StaticImage",str2[i]);
		imageGroup[i] ->setXPosition(CEGUI::UDim(0,0));
		imageGroup[i] ->setYPosition(CEGUI::UDim(0,0));
		float size = random(10,15);
		imageGroup[i] ->setSize(UVector2(UDim(0, size) ,UDim(0, size* 0.75f)));
		imageGroup[i] ->setProperty(("FrameEnabled"), ("false"));
		imageGroup[i] ->setProperty(("BackgroundEnabled"), ("false"));
		imageGroup[i] ->setMousePassThroughEnabled(true);
		//imageGroup[i] ->setAlwaysOnTop(true);
		imageGroup[i] ->setClippedByParent(false);
		imageGroup[i] ->setInheritsAlpha(false);
		if(i % 2 == 0){
			SakuraRain* sa = new SakuraRain(scaleGroup[i],imageGroup[i],"sakura","rotfall");
			sa->setSpeed(random(0.5,1.5));
			background->addChildWindow(scaleGroup[i]);
		}
		else{
			SakuraRain* sa = new SakuraRain(scaleGroup[i],imageGroup[i],"sakura","fall");
			sa->setSpeed(random(0.5,1.5));
			background->addChildWindow(scaleGroup[i]);
		} 
	}
	
	Window* serverAddressWindow = WindowManager::getSingleton().loadWindowLayout("ServerAddressWindow.layout");
	serverAddressWindow->getChild("ServerAddressWindow/SubmitButton")->subscribeEvent(PushButton::EventMouseClick,
		Event::Subscriber(&DaterApp::handle_SubmitServerAddress, this));

	System::getSingleton().getGUISheet()->addChildWindow(serverAddressWindow);
	serverAddressWindow->activate();
	/*

	Window* animationArea_1 = WindowManager::getSingleton().createWindow("WindowsLook/Static", "animationArea_1");
	animationArea_1->setProperty("UnifiedAreaRect", "{{0,100},{0,0},{0,350},{0,600}}");
	animationArea_1->setProperty("FrameEnabled", "false");
	animationArea_1->setProperty("BackgroundEnabled", "false");
	animationArea_1->setAlwaysOnTop(true);
	//animationArea_1->setMousePassThroughEnabled(true);

	Window* staticImage_1 = WindowManager::getSingleton().createWindow("WindowsLook/Static","staticImage_1");
	staticImage_1->setProperty("UnifiedAreaRect", "{{0,100},{0,100},{0,150},{0,130}}");
	staticImage_1->setClippedByParent(false);
	//staticImage_1->setProperty("FrameEnabled", "false");
	staticImage_1->setProperty("BackgroundEnabled", "false");
	//staticImage_1->setMousePassThroughEnabled(true);

	AnimationManager::getSingleton().loadAnimationsFromXML("Sakura.xml");
	AnimationManager::getSingleton().loadAnimationsFromXML("AnimationTrans.xml");

	Animation* animation_1 = AnimationManager::getSingleton().getAnimation("sakura");
	AnimationInstance* animationInstance_1 = AnimationManager::getSingleton().instantiateAnimation(animation_1);
	//animationInstance_1->setTarget(staticImage_1);
	

	Animation* animation_2 = AnimationManager::getSingleton().getAnimation("fall");
	AnimationInstance* animationInstance_2 = AnimationManager::getSingleton().instantiateAnimation(animation_2);
	//animationInstance_2->setTarget(staticImage_1);

	Animation* animation_3 = AnimationManager::getSingleton().getAnimation("alpha1");
	AnimationInstance* animationInstance_3 = AnimationManager::getSingleton().instantiateAnimation(animation_3);
	animationInstance_3->setTarget(staticImage_1);
	
	animationArea_1->addChildWindow(staticImage_1);
	background->addChildWindow(animationArea_1);

	Event::Connection connection = staticImage_1->subscribeEvent(animationInstance_2->EventAnimationStarted, Event::Subscriber(&DaterApp::handle_Register,this));
	staticImage_1->subscribeEvent(animationInstance_2->EventAnimationStopped, Event::Subscriber(&DaterApp::handle_Register,this));
	staticImage_1->subscribeEvent(animationInstance_2->EventAnimationEnded, Event::Subscriber(&DaterApp::handle_Register,this));
	staticImage_1->subscribeEvent(animationInstance_2->EventAnimationLooped, Event::Subscriber(&DaterApp::handle_Register,this));
	//staticImage_1->subscribeEvent(Window::EventMouseClick, Event::Subscriber(&CEGUI::AnimationInstance::handleStart, animationInstance_1));
	staticImage_1->subscribeEvent(Window::EventMouseClick, Event::Subscriber(&CEGUI::AnimationInstance::handleStart, animationInstance_3));

	*/

	//animationInstance_1->start();
	//animationInstance_2->start();
	/*Animation* animation_3 = AnimationManager::getSingleton().getAnimation("sakura2");
	AnimationInstance* animationInstance_3 = AnimationManager::getSingleton().instantiateAnimation(animation_3);
	animationInstance_3->setTarget(staticImage_1);
	animationInstance_3->start();

	Animation* animation_4 = AnimationManager::getSingleton().getAnimation("through");
	AnimationInstance* animationInstance_4 = AnimationManager::getSingleton().instantiateAnimation(animation_4);
	animationInstance_4->setTarget(staticImage_1);
	animationInstance_4->start();*/


	
    // load the initial layout
    //Window* DaterMainFrame = WindowManager::getSingleton().loadWindowLayout("DaterMain.layout");

	//background->addChildWindow(DaterMainFrame);

	//d_console = new TestConsole("");
	
	//EditEventWindow* editEventWindow = new EditEventWindow("",WindowManager::getSingleton().getWindow("Root"));
	//BaseWindowManager::getSingleton().addBaseWindow(editEventWindow);
	//_daterWindows[editEventWindow->getWindowName()] =  editEventWindow;

	//MainCalendarDayWindow* mainCalendarDayWindow = new MainCalendarDayWindow("",WindowManager::getSingleton().getWindow("Root"));
	//BaseWindowManager::getSingleton().addBaseWindow(mainCalendarDayWindow);
	//_daterWindows[mainCalendarDayWindow->getWindowName()] =  mainCalendarDayWindow;

	//MainCalendarMonthWindow* mainCalendarMonthWindow = new MainCalendarMonthWindow("",WindowManager::getSingleton().getWindow("Root"));
	//BaseWindowManager::getSingleton().addBaseWindow(mainCalendarMonthWindow);
	//_daterWindows[mainCalendarMonthWindow->getWindowName()] =  mainCalendarMonthWindow;

	//CalendarManagerWindow* calendarManagerWindow = new CalendarManagerWindow("",WindowManager::getSingleton().getWindow("Root")/*,WindowManager::getSingleton().getWindow("ScheduleWindow")*/);
	//BaseWindowManager::getSingleton().addBaseWindow(calendarManagerWindow);
	//_daterWindows[calendarManagerWindow->getWindowName()] =  calendarManagerWindow;

	//MainIconWindow* mainIconWindow = new MainIconWindow("",WindowManager::getSingleton().getWindow("Root/MainWindow"));
	//BaseWindowManager::getSingleton().addBaseWindow(mainIconWindow);
	//_daterWindows[mainIconWindow->getWindowName()] =  mainIconWindow;


	//calendarManagerWindow->setChildWindow(WindowManager::getSingleton().getWindow("CalendarWindow"));

	//calendarManagerWindow->setChildWindow(WindowManager::getSingleton().getWindow("ScheduleWindow"));

	//WindowManager& wmgr = WindowManager::getSingleton();

	//Window* preButtonWindow = 
		//wmgr .getWindow("DaterCalendarManager/CalendarManagerBar/Previous");

	//Window* nextButtonWindow = 
		//wmgr .getWindow("DaterCalendarManager/CalendarManagerBar/Next");

	//preButtonWindow->subscribeEvent(Window::EventMouseClick,
		//Event::Subscriber(&MainCalendarMonthWindow::setToPreMonth,mainCalendarMonthWindow));

	//nextButtonWindow->subscribeEvent(Window::EventMouseClick,
		//Event::Subscriber(&MainCalendarMonthWindow::setToNextMonth,mainCalendarMonthWindow));
	

	//default main window
	//mainIconWindow->showWindow();

    // setup events
    //subscribeEvents();

    // success!
    return true;
}

//----------------------------------------------------------------------------//
void DaterApp::cleanupSample()
{
    // nothing doing in here!
	//delete d_console;
}

void DaterApp::handleRecvMessage(std::string)
{
	int i = 1;
}

//----------------------------------------------------------------------------//
void DaterApp::exitApp()
{
	d_sampleApp->setQuitting();
}

//----------------------------------------------------------------------------//
void DaterApp::subscribeEvents()
{
    using namespace CEGUI;

    WindowManager& wmgr = WindowManager::getSingleton();

    /*
     * Subscribe handler to deal with user closing the frame window
     *//*
    CEGUI_TRY
    {
        Window* main_wnd = wmgr.getWindow("Root/MainWindow");
        main_wnd->subscribeEvent(
            FrameWindow::EventCloseClicked,
            Event::Subscriber(&DaterApp::handle_CloseButton, this));
    }
    // if something goes wrong, log the issue but do not bomb!
    CEGUI_CATCH(CEGUI::Exception&)
    {}*/

	wmgr.getWindow("Root/DailyInfoWindow/AddEventButton")->subscribeEvent(
		PushButton::EventClicked,
		Event::Subscriber(&DaterApp::handle_AddEvent,this));

	wmgr.getWindow("Root/UserWindow/RegisterButton")->subscribeEvent(
		PushButton::EventClicked,
		Event::Subscriber(&DaterApp::handle_Register,this));

	wmgr.getWindow("Root/UserWindow/LoginButton")->subscribeEvent(
		PushButton::EventClicked,
		Event::Subscriber(&DaterApp::handle_Login,this));

	wmgr.getWindow("Root/UserWindow/ExitButton")->subscribeEvent(
		PushButton::EventClicked,
		Event::Subscriber(&DaterApp::handle_Exit,this));
}


//----------------------------------------------------------------------------//
bool DaterApp::handle_CloseButton(const CEGUI::EventArgs&)
{
    d_sampleApp->setQuitting();
    return true;
}

//---------------------------------------------------------------------------//
bool DaterApp::handle_AddEvent(const CEGUI::EventArgs&)
{
	using namespace CEGUI;

	_daterWindows["FrameWindow"]->showWindow();
	
	return true;
}

bool DaterApp::handle_Register(const CEGUI::EventArgs&)
{
	using namespace CEGUI;

	_daterWindows["RegisterWindow"]->showWindow();

	return true;
}

bool DaterApp::handle_Login(const CEGUI::EventArgs&)
{
	using namespace CEGUI;

	_daterWindows["Login"]->showWindow();

	return true;
}

bool DaterApp::handle_Exit(const CEGUI::EventArgs&)
{
	using namespace CEGUI;

	/*Dater::XMLParserEvent eventToXml;
	eventToXml.createXmlFile();
	eventToXml.saveXmlFile();
	eventToXml.dropXmlFile();*/

    // signal quit
    d_sampleApp->setQuitting();

    // event was handled
    return true;
}

//////////////////////////////////////////////////////////////////////////
/*************************************************************************

    TestConsole class

*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// these must match the IDs assigned in the layout
const unsigned int TestConsole::SubmitButtonID = 1;
const unsigned int TestConsole::InputID        = 2;
const unsigned int TestConsole::OutputID       = 3;

TestConsole::TestConsole(const CEGUI::String& id_name, CEGUI::Window* parent) :
    _root(CEGUI::WindowManager::getSingleton().loadWindowLayout("DaterConsole.layout", id_name))
{
    using namespace CEGUI;

    // we will destroy the console box windows ourselves
    _root->setDestroyedByParent(false);

    // Do events wire-up
    _root->getChild(SubmitButtonID)->
        subscribeEvent(PushButton::EventClicked, Event::Subscriber(&TestConsole::handleSubmit, this));

    _root->getChild(InputID)->
        subscribeEvent(Editbox::EventTextAccepted, Event::Subscriber(&TestConsole::handleSubmit, this));

    // decide where to attach the console main window
    parent = parent ? parent : CEGUI::System::getSingleton().getGUISheet();

    // attach this window if parent is valid
    if (parent)
        parent->addChildWindow(_root);
}

TestConsole::~TestConsole()
{
    // destroy the windows that we loaded earlier
    CEGUI::WindowManager::getSingleton().destroyWindow(_root);
}

bool TestConsole::handleSubmit(const CEGUI::EventArgs&)
{
    using namespace CEGUI;

    // get the text entry editbox
    Editbox* editbox = static_cast<Editbox*>(_root->getChild(InputID));
    // get text out of the editbox
    String edit_text(editbox->getText());

	editbox->setText("");

	//sendMessageQueue.push(edit_text);*/
	/*
    // if the string is not empty
    if (!edit_text.empty())
    {
        // append newline to this entry
        edit_text += '\n';
        // get history window
        MultiLineEditbox* history = static_cast<MultiLineEditbox*>(d_root->getChild(OutputID));
        // append new text to history output
        history->setText(history->getText() + edit_text);
        // scroll to bottom of history output
        history->setCaratIndex(static_cast<size_t>(-1));
        // erase text in text entry box.
        editbox->setText("");
    }*/

    // re-activate the text entry box
    editbox->activate();

    return true;
}

bool DaterApp::handle_SubmitServerAddress(const CEGUI::EventArgs& args)
{
	using namespace CEGUI;

	std::string serverAdddress = WindowManager::getSingleton().getWindow("ServerAddressWindow/AddressInput")->getText().c_str();

	Dater::System::getSingleton().setServerAddress(serverAdddress);

	RegisterWindow* registerWindow = new RegisterWindow("", System::getSingleton().getGUISheet());
	BaseWindowManager::getSingleton().addBaseWindow(registerWindow);
	_daterWindows[registerWindow->getWindowName()] =  registerWindow;

	LoginWindow* loginWindow = new LoginWindow("", this, System::getSingleton().getGUISheet());
	BaseWindowManager::getSingleton().addBaseWindow(loginWindow);
	_daterWindows[loginWindow->getWindowName()] =  loginWindow;

	loginWindow->showWindow();

	WindowManager::getSingleton().destroyWindow("ServerAddressWindow");

	return true;
}